package com.hopu.controller;
import ch.qos.logback.core.OutputStreamAppender;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.ServletResponseWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("fileUpload")
public class UploadController {
    @RequestMapping ("upload")
    public String upload(@RequestBody byte[] file,String fileName) throws IOException {
        System.out.println("文件名：" + fileName+ "文件大小："+ file.length +"B");
        String newFileName = UUID.randomUUID().toString() +".mp4";
        FileOutputStream fileOutputStream =new FileOutputStream("c:/upload/" +fileName);
        fileOutputStream.write(file);
        fileOutputStream.close();
        return "ok";
    }
    @RequestMapping("file/{fileName}")
    public void  show(@PathVariable("fileName") String fileName , HttpServletResponse response) throws IOException {
        //I流传入文件上去
        FileInputStream fileInputStream = new FileInputStream("c:/upload/" +fileName);
        System.out.println("文件名：" + fileName);
        //O流，在服务器端接收
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("video/mp4");

        //使用byte数组接收并读取文件
        byte[] data =new byte[1024];
        int len =0;
        while ((len = fileInputStream.read(data)) != -1) {
            outputStream.write(data,0,len);
        }
        outputStream.close();
        fileInputStream.close();
    }
}
